package com.rpframework.website.device.act.api;

import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
/**
 * 聊天消息集成类
 * @author zhangli
 * @date 2016年3月16日 下午3:25:55
 */
public class ChatUtils {
	public static int CONNECT_TIMEOUT =20000;
	public static int SOCKET_TIMEOUT =20000;
	public static int CONNECTION_REQUEST_TIMEOUT =20000;
	public static final String REQUEST_HEAD = "https://a1.easemob.com/";//环信请求地址
	public static final String APP_KEY = "you-lin#youlin";//应用名称
	public static final String APP_CLIENT_ID = "YXA6snIZYK0nEeWxov2NzhDSKA";
	public static final String APP_CLIENT_SECRET = "YXA6yITJ5bNO26aL72fHNgJACFANBb4";
	public static String POST_URL;//请求地址
	public static final String TOKEN = "YWMtYQap_usnEeWmmucC5ec0eQAAAVSydr2a07dWIj-bCPdnynCI7kFVDaFjOEE";//token应7天获取一次 不能重复获取
	
	
	/**
	 * 获取token不要重复获取 七天有效
	 * @throws IOException
	 * @time 2016年3月16日 上午11:56:32
	 */
	public void test3() throws IOException{
		POST_URL = REQUEST_HEAD+APP_KEY.replace("#", "/")+"/"+"token";
		String grant_type = "client_credentials";
		String token = "{"+"'grant_type'"+":"+"'"+grant_type+"'"+","+"'client_id'"+":"+"'"+APP_CLIENT_ID+"'"+","+"'client_secret'"+":"+"'"+APP_CLIENT_SECRET+"'"+"}";
		token = token.replaceAll("\'", "\"");
		try {
			String body = secPost(POST_URL,token,"","");
			System.out.println(body.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 创建群组
	 * @param groupname 群组名
	 * @param desc 群组描述
	 * @param owner 群主
	 * @time 2016年3月16日 下午5:32:00
	 * 要返回群组id
	 * 每个小区都有个群组id 
	 * 后台物业公司添加一个小区时，就应自动创建一个当前小区的群组 desc为小区的名字 owner是当前物业的账号 groupname是小区的
	 */
	public void createGroups(String groupname,String desc,String owner){
		String createGroups="{"+"'groupname'"+":"+"'"+groupname+"'"+","+"'desc'"+":"+"'"+desc+"'"+","+"'public'"+":"+"true"+","+"'approval'"+":"+"true"+","+"'owner'"+":"+"'"+owner+"'"+"}";
		createGroups = createGroups.replaceAll("\'", "\"");
		String header = "Authorization";
		String value = "Bearer "+TOKEN;
		try {
			System.out.println(POST_URL);
			System.out.println(createGroups);
			String body = secPost(POST_URL,createGroups,header,value);
			System.out.println(body.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 注册的用户添加到小区的聊天群组里
	 * 获取小区的聊天群组id,获取物业的token
	 * @param account
	 * @param group_id
	 * @param token 7天获取一次 物业获取
	 * @return
	 * @time 2016年3月16日 下午5:15:50
	 */
	public static boolean addUserByGroups(String account,String group_id,String token){
		POST_URL = REQUEST_HEAD+APP_KEY.replace("#", "/")+"/"+"chatgroups/"+group_id+"/"+"users/"+account;
		//TOKEN = getToken();//这个token每个物业只能获取一次，且有效期为7天，怎么处理？
		String header = "Authorization";
		String value = "Bearer "+token;
		try {
			String body = secPost(POST_URL,"",header,value);
			System.out.println(body.toString());
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	/**
	 * 根据用户的手机号 密码注册环信用户
	 * 密码不能是MD5
	 * @param telphone
	 * @param password
	 * @time 2016年3月16日 下午3:26:28
	 */
	public static boolean registeasemob(String telphone, String password) {
		POST_URL = REQUEST_HEAD+APP_KEY.replace("#", "/")+"/"+"users";
		String header = "Content-Type";
		String value = "application/json";
		String username = telphone;
		String regist = "{"+"'username'"+":"+"'"+username+"'"+","+"'password'"+":"+"'"+password+"'"+"}";
		regist = regist.replaceAll("\'", "\"");
		try {
			String body = secPost(POST_URL,regist,header,value);
			System.out.println(body.toString());
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return true;
		}
	}
	/**
	 * 传入请求参数地址post_url,
	 * 请求body,
	 * 请求头header
	 * 请求头value
	 * @param url
	 * @param messageBody
	 * @param header
	 * @param value
	 * @return
	 * @throws Exception
	 * @time 2016年3月16日 下午3:30:23
	 */
	public static String secPost(String url, String messageBody,String header,String value)
			throws Exception {
		// 构建请求参数
		RequestConfig requestConfig = RequestConfig.custom()
									.setConnectTimeout(CONNECT_TIMEOUT)
									.setSocketTimeout(SOCKET_TIMEOUT)
									.setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
									.build();		
		String reqMsg = messageBody == null ? "" : messageBody;
		HttpEntity requestEntity = new StringEntity(reqMsg,"UTF-8");//FpsConstant.CHARSET_GBK
		HttpPost httppost = new HttpPost(url);
		httppost.setConfig(requestConfig);
		httppost.setEntity(requestEntity);
		//httppost.setHeader("Content-Type","application/json");
		httppost.setHeader(header,value);
		// 发送请求
		SSLContext sslcontext = new SSLContextBuilder().loadTrustMaterial(null,
				new TrustStrategy() {
					public boolean isTrusted(X509Certificate[] chain,
							String authType) throws CertificateException {
						return true;
					}
				}).build();
		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
		try{
			CloseableHttpResponse response = httpclient.execute(httppost);
			try{
				// 获取响应
				HttpEntity responseEntity = response.getEntity();
				// 提取响应信息
				String message = IOUtils.toString(responseEntity.getContent(),"UTF-8");
				EntityUtils.consume(responseEntity);
				return message;
			}finally{
				response.close();
			}
		}finally{
			httpclient.close();
		}
	}
}
